# src/core/config.py
from pydantic_settings import BaseSettings, SettingsConfigDict
from pydantic import Field, PostgresDsn, RedisDsn, AnyUrl
from pathlib import Path
from typing import Literal

class Settings(BaseSettings):
    # 项目元信息 
    PROJECT_NAME: str = Field("FastApi_RAG_Backend", description="fastapi知识库问答后端项目")
    PROJECT_VERSION: str = Field("1.0.0", description="项目版本")
    DEBUG: bool = Field(False, description="调试模式开关")

    # 数据库配置
    # 使用 PostgresDsn 类型自动验证 PostgreSQL 连接字符串格式
    DB_URI: PostgresDsn = Field(
        "postgresql+asyncpg://user:pass@localhost:5432/dbname",
        description="PostgreSQL 数据库连接字符串"
    )
    # 连接池大小等高级配置
    DB_POOL_SIZE: int = Field(20, ge=1, description="数据库连接池大小")
    DB_MAX_OVERFLOW: int = Field(10, ge=0, description="连接池最大溢出数")
    POOL_TIMEOUT: int = Field(15, ge=5, description="获得连接超时时间")
    POOL_RECYCLE: int = Field(4800, ge=10, description= "连接回收时间")
    POOL_PRE_PING: bool = Field(True, description="连接前是否预检查")

    # Redis配置
    REDIS_URL : RedisDsn = Field(
        "redis://localhost:6379/0",
        description="Redis连接配置"
    )

    # 安全配置 
    # SECRET_KEY: str = Field(..., description="用于加密的密钥，务必保密！") # 生产环境必须设置
    ALGORITHM: str = Field("HS256", description="JWT令牌签名算法")
    ACCESS_TOKEN_EXPIRE_MINUTES: int = Field(30, description="访问令牌过期时间（分钟）")

    # CORS 跨域配置 
    BACKEND_CORS_ORIGINS: list[str] = Field(["http://localhost:3000"], description="允许跨域请求的前端地址列表")

    # 外部API密钥等
    # SMTP_EMAIL: Optional[EmailStr] = None # 可选配置示例
    # REDIS_URL: Optional[str] = None

    # Pydantic V2 配置：从 .env 文件加载配置，并允许额外字段（兼容性）
    model_config = SettingsConfigDict(
        env_file=".env",
        env_file_encoding="utf-8",
        extra="ignore"
    )
    
    MEDIA_ROOT: Path = Field(default="media/uploads", description="用户上传文件（媒体文件）的存储根目录")
    MEDIA_URL: str = Field(default="/media/uploads", description="通过URL访问用户上传文件的前缀路径")

    PRELOAD_MODELS: bool = Field(True, description="是否进行预加载模型")

    IMAGE_EMBEDDING_MODEL_PATH:str = Field("weights/nomic-ai/nomic-embed-vision-v1.5")
    TEXT_EMBEDDING_MODEL_PATH:str = Field("weights/nomic-ai/nomic-embed-text-v1.5")
    TABLE_DETECT_MODEL_PATH:str = Field("weights/table_det.onnx")
    BGE_RERANKER_PATH:str = Field("weights/BAAI/bge-reranker-v2-m3")


    OLLAMA_MODEL:str = Field("qwen2.5vl:7b",description="默认Ollama模型")
    OLLAMA_API_URL: str = Field("http://localhost:11434/api/generate",description="Ollama API地址")
    OLLAMA_TIMEOUT: int = Field(180,description="API请求超时时间")
    OLLAMA_MAX_RETRIES:int = Field(3,description="API失败重试次数")

    #Neo4j配置
    NEO4J_URI: AnyUrl = Field("bolt://127.0.0.1:7687",description="Neo4j数据库连接URI")
    NEO4J_USER: str = Field("neo4j",description="Neo4j用户名")
    NEO4J_PASSWORD: str = Field("Cpgc@0215",description="Neo4j密码")

    # Neo4j 高级配置
    NEO4J_MAX_CONNECTION_POOL_SIZE: int = Field( 50, ge=1, description="Neo4j 连接池最大大小" )
    NEO4J_CONNECTION_TIMEOUT: int = Field(30, ge=1, description="Neo4j 连接超时时间（秒）")
    # 配置有些不正确，使用加密链接会导致链接失败，先不进行加密链接
    NEO4J_ENCRYPTED: bool = Field(False, description="是否使用加密连接" )
    NEO4J_TRUST_STRATEGY: Literal[ "TRUST_ALL_CERTIFICATES",
                                    "TRUST_SYSTEM_CA_SIGNED_CERTIFICATES",
                                    "TRUST_CUSTOM_CA_SIGNED_CERTIFICATES"
                            ] = Field(
                                "TRUST_ALL_CERTIFICATES",
                                description="证书信任策略"
                            )
    NEO4J_DATABASE: str = Field("neo4j", description="默认数据库名称" )
    NEO4J_QUERY_TIMEOUT: int = Field(60, ge=1, description="Cypher 查询超时时间（秒）")
    NEO4J_MAX_TRANSACTION_RETRY_TIME: int = Field(30, ge=1, description="事务重试最大时间（秒）")

# 创建全局配置实例
settings = Settings()
